package itheima.C02_xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.List;

public class Test2 {
    public static void main(String[] args) throws DocumentException {
        ArrayList<User> list = new ArrayList<>();
        //2.2使用解析器对象，
        //将xml文件解析为Document对象
        SAXReader reader = new SAXReader();
        Document doc=reader.read("day12_properties\\src\\itheima\\C02_xml\\users.xml");
        Element users =doc.getRootElement();
        //2.3获取根元素
        List<Element> usersElements = users.elements("user");
        for (Element usersElement : usersElements) {
            String ageStr = usersElement.elementText("age");
            int age = ageStr != null && !ageStr.isEmpty() ? Integer.parseInt(ageStr) : 0;
            
            String gender=usersElement.elementText("sex");
            String address=usersElement.elementText("address");

            Element nameEle=usersElement.element("name");
            String name=nameEle.elementText("name");
            
            String numStr = nameEle.elementText("num");
            int num = numStr != null && !numStr.isEmpty() ? Integer.parseInt(numStr) : 0;
            
            String idStr = nameEle.elementText("id");
            int id = idStr != null && !idStr.isEmpty() ? Integer.parseInt(idStr) : 0;
            //2.6 创建User对象，封装用户信息
            User user=new User(id,num,name,age,gender,address);
            list.add(user);
        }
        System.out.println("解析完毕。。。。");
        list.forEach(System.out::println);
    }
}
